import axios from 'axios'
import store from '@/store'
import NProgress from 'nprogress'
import 'nprogress/nprogress.css'

// 配置axios
const request = axios.create({
  baseURL: '/api',
  timeout: 5000 // 请求超时时间
})

// 请求拦截器
request.interceptors.request.use((config) => {
  // 开启进度条
  NProgress.start()
  // 判断是否有token
  if (store.state.user.token) {
    // 设置token
    config.headers.Authorization = `Bearer ${store.state.user.token}`
  }
  return config
})

// 响应拦截器
request.interceptors.response.use(
  (response) => {
    // 结束进度条
    NProgress.done()
    if (response.status === 200 || response.data.code === '1') {
      // 响应数据{msg: "操作成功",result:[{...},{...}]}
      // 处理响应数据
      return response.data.result // 直接接收result: []
    } else {
      alert(response.data.message)
      return Promise.reject(response.data.message)
    }
  },
  (error) => {
    // 结束进度条
    NProgress.done()
    alert(error)
    return Promise.reject(error)
  }
)

export default request
